package uk.org.landeg.euler.problems;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.apache.commons.math.geometry.Vector3D;

import uk.org.landeg.euler.problems.framework.AbstractProblem;
import uk.org.landeg.euler.problems.framework.ProblemLauncher;

public class Problem102 extends AbstractProblem {
	public static void main(String[] args) {
		ProblemLauncher launcher = new ProblemLauncher(new Problem102());
		launcher.solve();
	}

	@Override
	public String getDescription() {
		// TODO Auto-generated method stub
		return "find the number of triangles for which the interior contains the origin.";
	}

	@Override
	public Integer getProblemNumber() {
		// TODO Auto-generated method stub
		return 102;
	}

	@Override
	public Object solve() {
		BufferedReader reader = null;
		int count = 0, total = 0;
		boolean containsOrigin;
		Vector3D vab,vbc,vca,va0,vb0,vc0,ca,cb,cc;
		boolean p1,p2,p3;
		int ax=0,ay=1,bx=2,by=3,cx=4,cy=5;
		try {
			reader = new BufferedReader(new FileReader("data/triangles.txt"));
			String line = null;
			int coord[] = new int[6];
			while ((line = reader.readLine())!=null) {
				parseLine(line, coord);
				vab = new Vector3D((coord[bx] - coord[ax]), (coord[by] - coord[ay]), 0.0);
				vbc = new Vector3D((coord[cx] - coord[bx]), (coord[cy] - coord[by]), 0.0);
				vca = new Vector3D((coord[ax] - coord[cx]), (coord[ay] - coord[cy]), 0.0);

				va0 = new Vector3D((coord[ax]), (coord[ay]));
				vb0 = new Vector3D((coord[bx]), (coord[by]));
				vc0 = new Vector3D((coord[cx]), (coord[cy]));

				ca = Vector3D.crossProduct(vab, va0);
				cb = Vector3D.crossProduct(vbc, vb0);
				cc = Vector3D.crossProduct(vca, vc0);
				if (
					(ca.getZ() >= 0 && cb.getZ() >= 0 && cc.getZ() >= 0)
					|| (ca.getZ() <= 0 && cb.getZ() <= 0 && cc.getZ() <= 0)) {
						count++;
				}
//				System.out.println(line +"\t"+ containsOrigin);
				total++;
			}
			reader.close();
			notes.add("Total rows processed = " + total);
		} catch (FileNotFoundException e) {
			return e;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return e;
		}
		return count;
	}
	
	public static void parseLine (String line, int[] values) {
		if (values == null) {
			values = new int[6];
		}
		String toks[] = line.split(",");
		int idx = 0 ;
		for (String t : toks) {
			values[idx++] = Integer.parseInt(t);
		}
	}
	
	public boolean crossProductPositive (int a1, int a2, int b1, int b2) {
		int v1 = b1 - a1;
		int v2 = b2 - b2;
		int z = (b1 * v2) - (b2 * v1);
		if (z==0) {
			System.out.println("Warning : z = 0");
		}
		return (z > 0);
	}

}
